<?php
/**
 * 返款申请模型
 * (model)
 */
namespace App\Models\Reimburse;

use App\Models\Basics\SysCountry;
use App\Models\Basics\Currency;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use App\Util\User;
use Illuminate\Database\Eloquent\Model;
class ReimburseApply extends Model
{
    protected $table = 'reimburse_apply';

    protected $guarded = [];

    public static $_feeType = [
        1 => '刷单',
        2 => '广告',
        3 => '其他',
        4 => '自然留评',
    ];

    public static $_rType = [
        1 => 'FB刷单',
        2 => '中介刷单',
        3 => '真人刷单',
        4 => '乐天刷单',
        null => '',
    ];

    public static $_paidStatus = [
        1 => '未付款',
        2 => '部分付款',
        3 => '完全付款',
    ];

    public static $_applyStatus = [
        1 => '未申请',
        2 => '已申请'
    ];

    public static $_auditStatus = [
        1 => '未审核',
        2 => '已审核'
    ];

    public static $_paidType = [
        1 => '一次返款',
        2 => '多次返款',
        3 => '一次返款+佣金',
    ];

    public static $_paidMethod = [
        1 => '微信',
        2 => 'PayPal',
        3 => '银行卡',
        4 => '支付宝',
        5 => '预付费',
        6 => 'Amazon礼品卡',
    ];

    public static $_reviewStatus = [
        1 => '否',
        2 => '是',
        3 => '掉评',
    ];

    protected static function boot()
    {
        parent::boot();

        static::deleting(function($br) {
            $br->paid()->delete();
            $br->detail()->delete();
        });
    }

    public function paid(){
        return $this->hasMany(ReimbursePaid::class,'reimburse_no','reimburse_no');
    }

    /**
     * 返款明细
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function detail(){
        return $this->hasOne(ReimburseDetail::class,'reimburse_no','reimburse_no');
    }

    /**
     * 货币
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function currency()
    {
        return $this->belongsTo(Currency::class,'currency_code','code');
    }

    /**
     * 国家
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function country(){
        return $this->belongsTo(SysCountry::class,'country_id');
    }

    /**
     * sku
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    /**
     * 数据导出
     * @param $query
     */
    public static function exeDownload($query){
        $head = ['提报时间','审核状态','付款状态','费用类型','刷单类型','订单号/费用描述','提报单号','国家','销售员','亚马逊SKU','公司SKU','产品名称','品类'
            ,'支付方式','支付账号','返款类型','币种','订单联系人','备注','留评状态','留评链接','留评时间','佣金币种','佣金支付方式','佣金账号'
            ,'一次性返款','首次返款','二次返款','佣金'];
        RExcel::exportCsv('返款申请',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            $sellerId = $model->seller_id ?: 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $data1 = [
                $model->created_at,
                self::$_auditStatus[$model->audit_status],
                self::$_paidStatus[$model->paid_status],
                self::$_feeType[$model->fee_type],
                self::$_rType[$model->r_type],
                $model->order_no,
                $model->reimburse_no,
                $model->country->country ?? '',
                $seller[$sellerId],
                $model->seller_sku ?: '',
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                $model->skuClassify->title ?? '',
                self::$_paidMethod[$model->paid_method],
                $model->paid_account_no,
                self::$_paidType[$model->paid_type],
                $model->currency_code,
                $model->order_atten,
                $model->remarks,
                self::$_reviewStatus[$model->review_status],
                $model->review_link,
                $model->review_at
            ];
            $paid = [1=>[],2=>[],3=>[],4=>[]];$_paid_ = [];
            foreach($model->paid as $item){
                if($item->order_by == 1){
                    $paid[1] = $item;
                }elseif($item->order_by == 2){
                    $paid[2] = $item;
                }elseif($item->order_by == 3){
                    $paid[3] = $item;
                }elseif($item->order_by == 4){
                    $paid[4] = $item;
                    $_paid_ = $item;
                }
            }
            if(!empty($_paid_)){
                $data2 = [
                    $_paid_->currency_code,
                    $_paid_->paid_method ? self::$_paidMethod[$_paid_->paid_method] : '',
                    $_paid_->paid_account_no ?? '',
                ];
            }else{
                $data2 = [
                    '',
                    '',
                    ''
                ];
            }
            $data3 = [];
            foreach($paid as $k => $item){
                if(!empty($item)){
                    if($item->apply_status == 1){
                        $_item = ' 未申请';
                    }elseif($item->apply_status == 2 && $item->audit_status == 1){
                        $_item = ' 待审核';
                    }elseif($item->audit_status == 2 && $item->paid_status == 1){
                        $_item = ' 待付款';
                    }elseif($item->paid_status == 2){
                        $_item = ' 已付款';
                    }else{
                        $_item = ' 异常';
                    }
                    $data3['paid_amount_'.$k] = $item->paid_amount . $_item;
                }else{
                    $data3['paid_amount_'.$k] = '';
                }
            }
            $temp = array_merge($data1,$data2,$data3);
            yield $temp;
        }
    }
}
